package lesson.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lesson.entity.ChinaTotal;
import lesson.entity.LineTrend;
import lesson.entity.NocvData;
import lesson.entity.NocvNews;
import lesson.service.ChinaTotalService;
import lesson.service.IndexService;
import lesson.service.NocvNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description:
 * @Author: Wanzhen
 * @Date: 2022/6/8-22:37
 */
@Controller
public class IndexController {

    @Autowired
    private IndexService indexService;

    @Autowired
    private ChinaTotalService chinaTotalService;

    @Autowired
    private NocvNewsService nocvNewsService;

    /**
     * 主控页面，嵌套china
     * 查询chinaTotal最新的数据
     * @param model
     * @return
     */
    @RequestMapping("/")
    public String index(Model model) throws ParseException {
        //1.找到Id最大的一条数据
        Integer id = chinaTotalService.maxId();
        //2.根据Id进行查找数据
        ChinaTotal chinaTotal = chinaTotalService.getById(id);
        model.addAttribute("chinaTotal", chinaTotal);
       return "index";
    }

    //跳转china地图页面
    @RequestMapping("/toChina")
    public String toChina(Model model) throws ParseException {
        //1.找到Id最大的一条数据
        Integer id = chinaTotalService.maxId();
        //2.根据Id进行查找数据

        /**
         * Redis查询数据库的逻辑
         * ①查询Redis缓存，有数据，直接返回；②没有数据，查询Mysql数据库；③更新缓存，返回客户端
         */
        Jedis jedis = new Jedis("127.0.0.1");
        //①判断Redis是否连接上客户端
        if(jedis != null){
            String confirm = jedis.get("confirm");
            String input = jedis.get("input");
            String heal = jedis.get("heal");
            String dead = jedis.get("dead");
            String updateTime = jedis.get("updateTime");
            //缓存中有数据
            if(StringUtils.isNotBlank(confirm) && StringUtils.isNotBlank(input)
                && StringUtils.isNotBlank(heal) && StringUtils.isNotBlank(dead)
                && StringUtils.isNotBlank(updateTime)){
                ChinaTotal chinaTotalRedis = new ChinaTotal();
                chinaTotalRedis.setConfirm(Integer.parseInt(confirm));
                chinaTotalRedis.setInput(Integer.parseInt(input));
                chinaTotalRedis.setHeal(Integer.parseInt(heal));
                chinaTotalRedis.setDead(Integer.parseInt(dead));

                //格式调整 String --> Date
                //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //Date date = simpleDateFormat.parse(updateTime);
                //chinaTotalRedis.setUpdateTime(date); 刷新页面后解析不了，出现了问题
                chinaTotalRedis.setUpdateTime(new Date());
                System.out.println("redis中的数据:" + chinaTotalRedis);

                //查询到的数据放置于前台
                model.addAttribute("chinaTotal", chinaTotalRedis);
                //3.疫情播报新闻
                List<NocvNews> newsList = nocvNewsService.listNewsLimit5();
                model.addAttribute("newsList", newsList);
                return "china";
            }else {
                //②缓存中没有数据，去Mysql中查
                ChinaTotal chinaTotal = chinaTotalService.getById(id);
                model.addAttribute("chinaTotal", chinaTotal);
                List<NocvNews> newsList = nocvNewsService.listNewsLimit5();
                model.addAttribute("newsList", newsList);

                //更新缓存
                jedis.set("confirm",String.valueOf(chinaTotal.getConfirm()));
                jedis.set("input",String.valueOf(chinaTotal.getInput()));
                jedis.set("heal",String.valueOf(chinaTotal.getHeal()));
                jedis.set("dead",String.valueOf(chinaTotal.getDead()));
                jedis.set("updateTime",String.valueOf(chinaTotal.getUpdateTime()));

                return "china";
            }
        }
        //连接不上Redis，直接去Mysql中查
        ChinaTotal chinaTotal = chinaTotalService.getById(id);
        model.addAttribute("chinaTotal", chinaTotal);
        //3.疫情播报新闻
        List<NocvNews> newsList = nocvNewsService.listNewsLimit5();
        model.addAttribute("newsList", newsList);
        return "china";
    }

    /**
     * 每天更新一次的数据使用场景
     * @return
     * @throws ParseException
     */
    //查询疫情数据
    @RequestMapping("/query")
    @ResponseBody //返回json实体，在前台的ajax请求才能返回json对象
    public List<NocvData> queryData() throws ParseException {
        QueryWrapper<NocvData> queryWrapper = new QueryWrapper<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");  //查询当天的时间
        String format = simpleDateFormat.format(new Date());
        queryWrapper.ge("update_time", simpleDateFormat.parse(format));  //大于等于

        //1.先查看redis缓冲[list]，有数据返回即可
        Jedis jedis = new Jedis("127.0.0.1");
        if(jedis != null){ //查看是否连接了Redis数据库
            //1.1有缓存数据，返回数据即可
            // 获取存储的数据并输出
            List<String> listRedis = jedis.lrange("nocvdata", 0 ,33);
            List<NocvData> dataList = new ArrayList<>();
            if(listRedis.size() > 0){
                for(int i=0; i<listRedis.size(); i++) {
                    System.out.println("列表项为: "+listRedis.get(i));
                    String strJson = listRedis.get(i);
                    JSONObject jsonObject = JSONObject.parseObject(strJson);
                    Object name = jsonObject.get("name");
                    Object value = jsonObject.get("value");
                    NocvData nocvData = new NocvData();
                    nocvData.setName(String.valueOf(name));
                    nocvData.setValue(Integer.parseInt(value.toString()));
                    dataList.add(nocvData);
                }
                //查询redis缓存数据库，返回的数据
                return dataList;
            }else {
                //1.2redis没有数据，就去查Mysql数据库，更新缓存
                List<NocvData> list = indexService.listOrderByIdLimit34();
                for (NocvData nocvData : list){
                    //将json格式的数据转换为字符串，再置入redis的list列表的值中
                    jedis.lpush("nocvdata", JSONObject.toJSONString(nocvData));
                }
                //返回数据库中的数据
                return list;
            }
        }

        //1.3默认没有连接redis的返回数据库[兼容没有安装redis]
        List<NocvData> list = indexService.listOrderByIdLimit34();
        return list;
    }

    //跳转Pie页面
    @RequestMapping("/toPie")
    public String toPie(){
        return "pie";
    }

    //分组聚合
    @RequestMapping("/queryPie")
    @ResponseBody
    public List<NocvData> queryPieData(){

        List<NocvData> list = indexService.listOrderByIdLimit34();
        return list;
    }

    //跳转柱状图页面
    @RequestMapping("/toBar")
    public String toBar(){
        return "bar";
    }

    @RequestMapping("/queryBar")
    @ResponseBody
    public Map<String, List<Object>> queryBarData(){
        //1.所有省份数据：数值
        List<NocvData> list = indexService.listOrderByIdLimit34();
        //2.所有省份数据
        List<String> provinceList = new ArrayList<>();
        //3.所有疫情数值数据
        List<Integer> dataList = new ArrayList<>();
        //封装数据
        for (NocvData data : list){
            provinceList.add(data.getName());
            dataList.add(data.getValue());
        }
        //4.创建map
        Map map = new HashMap();
        map.put("provinceList", provinceList);
        map.put("dataList", dataList);

        return map;
    }

    //跳转折线图页面
    @RequestMapping("/toLine")
    public String toLine(){
        return "line";
    }

    //使用自己写的sql语句
    @RequestMapping("/queryLine")
    @ResponseBody
    public Map<String, List<Object>> queryLintDate(){
        //1.查询近七天所有的数据
        List<LineTrend> lists = indexService.fineSevenDate();
        /*
         以下数据返回给前台
         */
        //2.封装所有的确诊人数
        List<Integer> confirmList = new ArrayList<>();
        //3.封装所有的隔离人数
        List<Integer> isolationList = new ArrayList<>();
        //4.封装所有的治愈人数
        List<Integer> cureList = new ArrayList<>();
        //5.封装所有的死亡人数
        List<Integer> deadList = new ArrayList<>();
        //6.封装所有的疑似人数
        List<Integer> similarList = new ArrayList<>();
        for(LineTrend trend: lists){
            confirmList.add(trend.getConfirm());
            isolationList.add(trend.getIsolation());
            cureList.add(trend.getCure());
            deadList.add(trend.getDead());
            similarList.add(trend.getSimilar());
        }
        //7.返回数据的格式容器Map
        Map map = new HashMap();
        map.put("confirmList", confirmList);
        map.put("isolationList", isolationList);
        map.put("cureList", cureList);
        map.put("deadList", deadList);
        map.put("similarList", similarList);

        return map;
    }

}
